#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <ctype.h>
#include <sys/time.h>

#define MAX 10000000
int data[MAX];
int indexs = 0;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

// return us
long get_interval(struct timeval tv_start,struct timeval tv_end){
    long start_us = tv_start.tv_sec * 1000000 + tv_start.tv_usec;
    long end_us   = tv_end.tv_sec   * 1000000 + tv_end.tv_usec;
    return end_us - start_us;
}

void * thread0(void * arg)
{
    int i = 0;
    while(indexs<MAX && i <= MAX)
    {
        pthread_mutex_lock(&mut);
        for(int j = 0;j<200 && indexs < MAX && i <=MAX;j++)
        {
            // critical section
            data[indexs] = i;
            indexs ++;
            // should be done together
            i+=2;
        }
        pthread_mutex_unlock(&mut);
    }
}

void * thread1(void * arg)
{
    int i = 0;
    while(indexs<MAX && i < MAX)
    {
        pthread_mutex_lock(&mut);
        for(int j = 0;j<200 && indexs < MAX && i<MAX;j++)
        {
            // critical section
            data[indexs] = i+1;
            indexs ++;
            // should be done together
            i+=2;
        }
        pthread_mutex_unlock(&mut);
    }
}

int main()
{
    pthread_t t0,t1;
    int max_gap = 0;
    int new_gap;
    // mut 
    struct timeval tv1,tv2;
    gettimeofday(&tv1,NULL);
    
    pthread_create(&t0,NULL,thread0,NULL);
    pthread_create(&t1,NULL,thread1,NULL);

    pthread_join(t0,NULL);
    pthread_join(t1,NULL);
    gettimeofday(&tv2,NULL);
    printf("Time: %ld\n",get_interval(tv1,tv2));


    for(int k = 0;k<MAX-1;k++)
    {
        new_gap = abs(data[k+1]-data[k]);
        if(new_gap > max_gap)
        {
            // printf("refresh to %d - %d = %d\n",data[k+1],data[k],new_gap);
            max_gap = new_gap;
        }
    }
    int have_zero = 0;
    for(int k = 0;k<MAX;k++)
    {
        if(have_zero && data[k] == 0)
            printf("Lost at %d\n",k);
        else if(!have_zero && data[k] == 0)
            have_zero = 1;
    }

    // printf("Max gap: %d\n",max_gap);
    // printf("%d\n",max_gap);
    return 0;
}